package LeetCode.leetcode;

/**
 * 在排序数组中查找元素的第一个和最后一个位置
 * 输入: nums = [5,7,7,8,8,10], target = 8
 * 输出: [3,4]
 * @author: leiwenkang02@meituan.com
 * @date: 2018/10/26
 * @time: 18:25
 */
public class Test34在排序数组中查找元素的第一个和最后一个位置 {
    public static void main(String[] args) {
        Test34在排序数组中查找元素的第一个和最后一个位置 test34在排序数组中查找元素的第一个和最后一个位置 = new Test34在排序数组中查找元素的第一个和最后一个位置();
        int[] nums = {5,7,7,8,8,10};
        int[] result = test34在排序数组中查找元素的第一个和最后一个位置.searchRange(nums, 8);
        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }
    }
    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[2];
        if (nums == null || nums.length == 0) {
            result[0] = -1;
            result[1] = -1;
            return result;
        }
        result[0] = getFirstNum(nums, target);
        result[1] = getLastNum(nums, target);
        return result;

    }

    private int getFirstNum(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (nums[mid] == target) {
                if (mid == start || nums[mid - 1] != nums[mid]) {
                    return mid;
                } else {
                    end = mid - 1;
                }
            } else if (nums[mid] < target) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return -1;
    }

    private int getLastNum(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (nums[mid] == target) {
                if (mid == end || nums[mid + 1] != nums[mid]) {
                    return mid;
                } else {
                    start = mid + 1;
                }
            } else if (nums[mid] < target) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return -1;
    }
}
